<?php
/**
* Copyright (c) 2009, Fabio Kreusch
*
* Licensed under The MIT License
* Redistributions of files must retain the above copyright notice.
* @copyright            Copyright (c) 2009, Fabio Kreusch
* @link                 fabio.kreusch.com.br
* @license              http://www.opensource.org/licenses/mit-license.php The MIT License
*/
class Subscription extends NewsletterAppModel {

  var $name = 'Subscription';
  var $primaryKey = 'id';
  var $displayField = 'email';
  var $useTable = 'newsletter_subscriptions';
  
	var $actsAs   = array('extendAssociations'); 
	var $validate = array(
		'name' => array( 
			VALID_NOT_EMPTY,
			array(
				'rule' => array('maxLength', 200)
			)
		),
		'email' => array( 
			VALID_NOT_EMPTY,
			array(
				'rule'=> 'email'
			)
		)
	);
	
	var $hasAndBelongsToMany = array(
				'Group' => array(
					'className' => 'Newsletter.Group',
					'joinTable' => 'newsletter_groups_subscriptions',
					'foreignKey' => 'newsletter_subscription_id',
					'associationForeignKey' => 'newsletter_group_id',
					'unique' => true,
				)
		);
	
	/*
	*/
	

	function importCsv($data, $groups=array()) {
	  $this->insertMulti(array('email', 'name'),	$data); 	
	  
	  if(!empty($groups)) {
	    $emails = array();
	    foreach ($data as $value) {
	      array_push($emails, $value[0]);
	    }
	    
	    $this->unbindModel(array('hasAndBelongsToMany' => array('Group')));
	    $ids = $this->find('all', array('fields' => array('id'), 'conditions' => array('email' => $emails)));
	    
	    $values = array();
	    foreach ($ids as $id) {
	      foreach ($groups as $group_id) {
	        array_push($values, array($id['Subscription']['id'], $group_id));
	      }
	    }
	    
	    $this->insertMulti(array('newsletter_subscription_id', 'newsletter_group_id'),	$values, 'newsletter_groups_subscriptions');
	  }	
	}
	
}
?>
